<template>
  <div>
    <div>
      <el-form :inline="true">
        <el-form-item style="margin-left: 10px">
          <el-button type="primary" :disabled="disable">其他资料上传</el-button>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button type="text" @click="dialogTableVisible = true" :disabled="disable">修改意见</el-button>

          <el-dialog title="修改意见" :visible.sync="dialogTableVisible">
            <el-input type="textarea" v-model="ruleForm.suggestion"></el-input>
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="22">
      <el-col :span="10">
        <el-divider content-position="center">专利申请书</el-divider>
        <div style="margin-bottom: 20px;">
          <el-button
              type="primary" plain
              @click="addTab(editableTabsValue)"
              :disabled="disable"
          >
            新增申请人
          </el-button>
        </div>
        <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab" tab-position="left">
          <el-tab-pane
              v-for="(item, index) in editableTabs"
              :key="item.name"
              :label="item.title"
              :name="item.name"
          >
            <el-form :model="item.content" :rules="rules" ref="item.content" label-width="100px" class="demo-ruleForm">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="item.content.name" clearable :disabled="disable"></el-input>
              </el-form-item>
              <el-form-item label="身份证号码" prop="identity">
                <el-input v-model="item.content.identity" clearable :disabled="disable"></el-input>
              </el-form-item>
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input v-model="item.content.nativePlace" clearable :disabled="disable"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="telephone">
                <el-input v-model="item.content.telephone" clearable :disabled="disable"></el-input>
              </el-form-item>
              <el-form-item label="邮政编码" prop="code">
                <el-input v-model="item.content.code" clearable :disabled="disable"></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="address">
                <el-input v-model="item.content.address" clearable :disabled="disable"></el-input>
              </el-form-item>
              <el-form-item label="设为联系人" prop="contact">
                <el-switch v-model="item.content.contact" @change="contact(index)" :disabled="disable"></el-switch>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm1('item.content',index)" :disabled="disable">立即创建
                </el-button>
                <el-button @click="resetForm1('item.content',index)" :disabled="disable">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>

      <el-col :span="10">
        <el-divider content-position="center" style="width: 80px">专利说明书</el-divider>
        <el-form :model="ruleForm" :rules="rules1" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="专利名称" prop="name">
            <el-input v-model="ruleForm.name" clearable :disabled="disable"></el-input>
          </el-form-item>
          <el-form-item label="专利简介" prop="content">
            <el-input type="textarea" v-model="ruleForm.content" :disabled="disable"></el-input>
          </el-form-item>
          <el-form-item label="技术领域" prop="field">
            <el-input type="textarea" v-model="ruleForm.field" clearable :disabled="disable"></el-input>
          </el-form-item>
          <el-form-item label="背景技术" prop="background">
            <el-input type="textarea" v-model="ruleForm.background" clearable :disabled="disable"></el-input>
          </el-form-item>
          <el-form-item label="专利内容" prop="introduce">
            <el-input type="textarea" v-model="ruleForm.introduce" clearable :disabled="disable"></el-input>
          </el-form-item>
          <el-form-item label="专利类型" prop="type">
            <el-radio-group v-model="ruleForm.type" :disabled="disable">
              <el-radio label="外观专利"></el-radio>
              <el-radio label="实用新型专利"></el-radio>
              <el-radio label="发明专利"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="代理人" prop="helper">
            <el-radio-group v-model="ruleForm.helper" v-for="item in helpers" @change="helper(item)">
              <el-radio :label="item.name" style="margin-left: 3px" :disabled="disable"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')" :disabled="disable">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')" :disabled="disable">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-col :span="2">
        <div style="margin-top: 35px" v-for="item in helpers">
          <el-popover
              placement="left"
              :title="item.name"
              width="200"
              trigger="hover"
          >
            <p>年龄：{{ item.age }}</p>
            <p>擅长领域：{{ item.advantage }}</p>
            <p>从业经历：{{ item.experience }}</p>
            <p>成功案例：{{ item.successCase }}件</p>
            <el-button slot="reference">{{ item.name }}</el-button>
          </el-popover>
        </div>

        <el-button type="primary" plain style="margin-top: 20px" @click="getHelpers" :disabled="disable">换一批</el-button>
      </el-col>
    </el-row>
  </div>

</template>

<script>
export default {
  name: "PatentApplication",
  data() {
    return {
      dialogTableVisible: false,

      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        identity: [
          {required: true, message: '请输入身份证号码', trigger: 'blur'},
          {min: 18, max: 18, message: '长度在为18个字符', trigger: 'blur'}
        ],
        nativePlace: [
          {required: true, message: '请输入籍贯', trigger: 'blur'}
        ],
        telephone: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {min: 11, max: 11, message: '长度在为11个字符', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入邮政编码', trigger: 'blur'},
          {min: 6, max: 6, message: '长度在为6个字符', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'}
        ],
      },

      editableTabsValue: '1',
      editableTabs: [{
        title: '申请人1',
        name: '1',
        content: {
          name: '',
          identity: '',
          nativePlace: '',
          telephone: '',
          code: '',
          address: '',
          contact: false,
        },
      }],
      hasContact: false,
      tabIndex: 1,
      addIndex: 1,
      currentIndex: 1,
      applicants: [],
      //第二张表单
      ruleForm: {
        name: '',
        field: '',
        background: '',
        content: '',
        type: '外观专利',
        //当查询出代理人后，默认为第一个
        helper: '',
        helperId: 0,
        introduce: '',
        suggestion: '',
      },
      applicantIds: [],
      contactId: 0,

      rules1: {
        name: [
          {required: true, message: '请输入专利名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        field: [
          {required: true, message: '请填写专利领域', trigger: 'blur'}
        ],
        background: [
          {required: true, message: '请填写专利背景技术', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请填写专利内容', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择专利类型', trigger: 'change'}
        ],
        helper: [
          {required: true, message: '请选择代理人', trigger: 'change'}
        ],
        introduce: [
          {required: true, message: '请填写专利简介', trigger: 'blur'}
        ]
      },
      //第三列
      helpers: [],
      b: 1,
      allApplicantIds: [],
      disable: false,
    };
  },
  created() {
    this.getHelpers();
    //查询专利及申请人信息
    if (this.$route.params.patentId!=undefined&&this.$route.params.patentId!=null) {
      //查询专利及申请人信息
      this.$axios.get('/patent/selectD/' + this.$route.params.patentId)
          .then(res => {
            console.log(res.data);
            this.ruleForm = res.data.data;
            this.$axios.get('/patent/selectP&A/' + this.$route.params.patentId)
                .then(res => {
                  console.log(res.data);
                  this.editableTabs = [];
                  this.tabIndex = 0;
                  this.addIndex = 0;
                  res.data.data.patent.applicants.forEach(applicant => {
                    if (applicant.hasContact == true) {
                      applicant.contact = true;
                      this.hasContact = true;
                    }
                    let newTabName = ++this.tabIndex + '';
                    this.editableTabs.push({
                      title: '申请人' + ++this.addIndex,
                      name: newTabName,
                      content: applicant,
                    });
                    this.editableTabsValue = newTabName;
                    this.currentIndex = newTabName;
                    this.applicantIds.push(applicant.id);
                  });
                  this.helpers[0] = res.data.data.helper;
                  this.ruleForm.helper = res.data.data.helper.name;
                });
          });
    }
    this.disable = this.$route.params.disable;
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/patent/add', this.ruleForm)
              .then(res => {
                this.$axios.post('/patent/addP&A/' + this.contactId + '/' + res.data.data.id, this.applicantIds)
                    .then(res => {
                      this.$message({
                        message: '恭喜你，操作成功！',
                        type: 'success'
                      });
                    })
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    submitForm1(formName, index) {
      this.$refs[formName][0].validate((valid) => {
        if (valid) {
          if (this.hasContact === false) {
            this.$message.error('没有设置联系人！');
          } else {
            this.editableTabs.forEach(tab => {
              this.applicants.push(tab.content);
            })
            this.allApplicantIds = [];
            this.$axios.post('/applicant/delete', this.applicantIds).then(res => {
              this.applicantIds.forEach(id => {
                this.allApplicantIds.push(id);
              });
              this.$axios.post('/applicant/add', this.applicants).then(res => {
                this.$message({
                  message: '恭喜你，操作成功！',
                  type: 'success'
                });
                this.applicantIds = res.data.data;
                this.applicantIds.forEach(id => {
                  this.allApplicantIds.push(id);
                });
                this.applicants = [];

                console.log("hebingshuzu:");
                console.log(this.allApplicantIds);
                this.$axios.post('/applicant/updateP&A', this.allApplicantIds).then(res => {
                  console.log(res.data);
                });
              })
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resetForm1(formName, index) {
      this.$refs[formName][index].resetFields();
    },
    addTab(targetName) {
      if (this.editableTabs.length >= 3) {
        this.$message({
          message: '申请人人数不能超过三个',
          type: 'warning'
        });
      } else {
        let newTabName = ++this.tabIndex + '';
        this.editableTabs.push({
          title: '申请人' + ++this.addIndex,
          name: newTabName,
          content: {
            name: '',
            identity: '',
            NativePlace: '',
            telephone: '',
            code: '',
            address: '',
            contact: false,
          },
        });
        this.editableTabsValue = newTabName;
        this.currentIndex = newTabName;
      }
    },
    removeTab(targetName, index) {
      if (this.disable == true) {
        his.$message.error('你没有权限修改！');
      } else {
        if (this.editableTabs.length <= 1) {
          this.$message({
            message: '申请人最少要有一个',
            type: 'warning'
          });
        } else {
          let tabs = this.editableTabs;
          let activeName = this.editableTabsValue;
          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                let nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }
          this.editableTabsValue = activeName;
          this.editableTabs = tabs.filter(tab => tab.name !== targetName);
          let t = 1;
          this.editableTabs.map((tab, index) => {
            tab.title = "申请人" + (index + 1);
            this.addIndex = (index + 1);
            if (tab.content.contact === true) {
              t = 0;
            }
          });
          if (t === 1) {
            this.hasContact = false;
          }
          this.currentIndex = this.editableTabsValue;

        }
      }
    },
    contact(index) {
      if (this.hasContact === false) {
        this.hasContact = true;
        this.contactId = index;
      } else if (this.hasContact === true && this.editableTabs[index].content.contact === false) {
        this.hasContact = false;
      } else if (this.hasContact === true) {
        this.editableTabs[index].content.contact = false;
        this.$message.error('不能重复设置联系人！');
      }
    },
    helper(item) {
      this.ruleForm.helperId = item.id;
    },
    getHelpers() {
      if (this.b > 2) {
        this.b = 1;
      }
      this.$axios.get('/helper/select/' + this.b).then(res => {
        this.helpers = res.data.data;
        this.ruleForm.helperId = this.helpers[0].id;
        this.ruleForm.helper = this.helpers[0].name;
        this.b++;
      });
    },
  }
}
</script>

<style scoped>
.el-row {
  display: flex;
  justify-content: center;
}

.el-col {
  border-radius: 4px;

}

.row-bg {
  padding: 20px 0;
  background-color: #f9fafc;
}
</style>